# Simple PowerShell HTTP Server

# Create and configure listener
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add("http://localhost:8080/")
$listener.Start()

Write-Host "Server running at http://localhost:8080"
Write-Host "Press Ctrl+C to stop the server"

# Create a stopwatch to track uptime
$startTime = Get-Date

# Main loop to handle requests
while ($listener.IsListening) {
    # Use try-catch to handle any exceptions during request processing
    try {
        # Wait for a request with a timeout to allow checking for stop signals
        if ($listener.Pending()) {
            $context = $listener.GetContext()
            $request = $context.Request
            $response = $context.Response
            
            # Log the request
            Write-Host "Request: $($request.HttpMethod) $($request.Url.LocalPath)"
            
            # Set response headers and content
            $response.StatusCode = 200
            $response.ContentType = "text/html"
            
            # Create a simple HTML response
            $htmlContent = @"
<html>
<body>
    <h1>Server Running!</h1>
    <p>Current time: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")</p>
    <p>Uptime: $((Get-Date) - $startTime)</p>
    <p>Request path: $($request.Url.LocalPath)</p>
</body>
</html>
"@
            
            # Convert to bytes and send response
            $buffer = [System.Text.Encoding]::UTF8.GetBytes($htmlContent)
            $response.ContentLength64 = $buffer.Length
            $output = $response.OutputStream
            $output.Write($buffer, 0, $buffer.Length)
            $output.Close()
            
            Write-Host "Response sent: 200 OK"
        } else {
            # Small sleep to prevent CPU usage while waiting for requests
            Start-Sleep -Milliseconds 100
        }
    } catch {
        # Log any errors
        Write-Host "Error: $_"
    }
}

# Cleanup (this code will only execute if the listener is stopped)
Write-Host "Server stopped"